package com.aliyun.heiyu.powermaster.server.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class MasterThreadFactory implements ThreadFactory {
    private static final Logger logger = LoggerFactory.getLogger(MasterThreadFactory.class);

    private final ThreadGroup group;
    private final static AtomicInteger poolNumber = new AtomicInteger(1);
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public MasterThreadFactory(String poolName) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (null == poolName || poolName.isEmpty()) {
            poolName = "pool";
        }
        namePrefix = poolName + "-pool-" + poolNumber.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group,r,namePrefix + threadNumber.getAndIncrement(), 0);
        t.setUncaughtExceptionHandler(new MyUncheckedExceptionhandler());
        return t;
    }

    private class MyUncheckedExceptionhandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error(e.getMessage(), e);
        }
    }
}
